﻿#include "ZmqSendReplyClient.h"
#define CHAR_MAX_LENGTH        1024    //使用的字符串最大长度
#include "WaitUtils.h"
#include "DialogSendReply.h"
#include "QtConcurrent/QtConcurrent"
#include "zmq.h"

ZmqSendReplyClient::ZmqSendReplyClient()
{

}

bool ZmqSendReplyClient::Connect()
{
    _context=zmq_ctx_new();
    _socket=zmq_socket(_context,ZMQ_REQ);
    int rc=zmq_connect(_socket,  _communicationParam.toUtf8().data());

    if(rc!=0)
    {
        return false;
    }

    int timeout=3000;
    if(zmq_setsockopt(_socket, ZMQ_RCVTIMEO, &timeout, sizeof(int)) < 0)
    {
        qDebug()<<"Failed to setsocketopt ZMQ_RCVTIMEO error";
    }
    return true;
}

bool ZmqSendReplyClient::SendReply(QByteArray sendBuff, QByteArray &receiveBuff)
{
    char receivetMsg[CHAR_MAX_LENGTH*10] = {'\0'};
    int tryTimes = 0;
    bool success = false;

    for (int i = 0; i < 3; ++i)
    {
        int sendLen = zmq_send(_socket, sendBuff.data(), sendBuff.length(), 0);
        if (sendLen >= 0)
        {
            // 等待一段时间，这里可以根据具体情况调整
            WaitUtils::WaitMsNoException(100);

            // 接收数据时获取实际接收的长度
            int recvLen = zmq_recv(_socket, receivetMsg, sizeof(receivetMsg) - 1, 0);
            if (recvLen >= 0)
            {
                receivetMsg[recvLen] = '\0'; // 添加字符串结尾
                receiveBuff = QByteArray(receivetMsg, recvLen);
                qDebug() << "Received length:" << receiveBuff.length();
                success = true;
                break;
            }
        }
        tryTimes++;
    }

    return success;
}

QDialog *ZmqSendReplyClient::GetConfigWidget()
{
    DialogSendReply *w=new DialogSendReply();
    w->SetSendReply(this);
    return w;
}

void ZmqSendReplyClient::Dispose()
{
    zmq_close (_socket);
    zmq_ctx_destroy (_context);
}
